package com.windoent.yugioh.ui.fragment.point;

import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.baidu.mobstat.StatService;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;
import com.windoent.yugioh.R;
import com.windoent.yugioh.adapter.brvah.PointIntegralRankAdapter;
import com.windoent.yugioh.base.BaseFragment;
import com.windoent.yugioh.bean.RankListBean;
import com.windoent.yugioh.bean.eventbus.MessageEvent;
import com.windoent.yugioh.bean.eventbus.PointEvent;
import com.windoent.yugioh.constants.Constants;
import com.windoent.yugioh.http.PhoneLive;
import com.windoent.yugioh.ui.activity.point.SelectSeasonRewardGetAddressActivity;
import com.windoent.yugioh.utils.BaseUtils;
import com.windoent.yugioh.utils.SimpleUtils;
import com.windoent.yugioh.utils.ToastUtils;
import com.windoent.yugioh.widget.RoundImageView;
import com.windoent.yugioh.widget.dialog.SeasonRewardDialog;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;

import java.util.List;

import okhttp3.Call;

/**
 * author : robert
 * date   : 2021/4/28 18:11
 * desc   :简中榜单
 */
public class JanePointFragment extends BaseFragment {

    private LinearLayout mLlBottom;
    private RoundImageView mIvBottomAvatar;
    private TextView mTvBottomName;
    private TextView mTvBottomPaiming;
    private TextView mTvBottomPointSaijiIntegration;
    private RecyclerView mRecyclerView;
    private SmartRefreshLayout mSmartLayout;

    private RelativeLayout mRlOne;
    private String type = "1";//类型： 1:简中 2：日文
    private String season_id = "";//选中赛季的id

    private String limit = Constants.PAGETEN;
    private int mCount = 1;
    private PointIntegralRankAdapter adapter;

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_jane_point;
    }

    public static JanePointFragment newsInstance() {
        return new JanePointFragment();
    }

    @Override
    protected void initEventAndData() {
        EventBus.getDefault().register(this);
        initView();
        initData();
    }

    private void initData() {
        mTvBottomPaiming.setText(String.format(mContext.getString(R.string.string_bottom_point_paiming), 287));
        mTvBottomPointSaijiIntegration.setText("1276");
        initAdapter();
    }


    private void initView() {
        mLlBottom = (LinearLayout) mView.findViewById(R.id.ll_bottom);
        mIvBottomAvatar = (RoundImageView) mView.findViewById(R.id.iv_bottom_avatar);
        mTvBottomName = (TextView) mView.findViewById(R.id._tv_bottom_name);
        mTvBottomPaiming = (TextView) mView.findViewById(R.id._tv_bottom_paiming);
        mTvBottomPointSaijiIntegration = (TextView) mView.findViewById(R.id.tv_bottom_point_saiji_integration);
        mRecyclerView = (RecyclerView) mView.findViewById(R.id.recycler_view);
        mSmartLayout = (SmartRefreshLayout) mView.findViewById(R.id.smart_layout);
    }

    //前三名
    private void addHeader(PointIntegralRankAdapter adapter, List<RankListBean.DataBean.PersonalBean> subList) {
        if (isAdded() && getActivity() != null) {
            View headView = getLayoutInflater().inflate(R.layout.fragment_point_three, (ViewGroup) mRecyclerView.getParent(), false);

            RoundImageView mIvPointAvatarTwo = (RoundImageView) headView.findViewById(R.id.iv_point_avatar_two);
            TextView mTvPointTwoName = (TextView) headView.findViewById(R.id.tv_point_two_name);
            TextView mTvPointTwoNamePoint = (TextView) headView.findViewById(R.id.tv_point_two_name_point);
            RoundImageView mIvPointAvatarOne = (RoundImageView) headView.findViewById(R.id.iv_point_avatar_one);
            TextView mTvPointOneName = (TextView) headView.findViewById(R.id.tv_point_one_name);
            TextView mTvPointOneNamePoint = (TextView) headView.findViewById(R.id.tv_point_one_name_point);
            RoundImageView mIvPointAvatarThree = (RoundImageView) headView.findViewById(R.id.iv_point_avatar_three);
            TextView mTvPointThreeName = (TextView) headView.findViewById(R.id.tv_point_three_name);
            TextView mTvPointThreeNamePoint = (TextView) headView.findViewById(R.id.tv_point_three_name_point);

            SimpleUtils.loadImageForView(mContext, mIvPointAvatarTwo, subList.get(1).getAvatar(), R.drawable.img_official_avatar_android);
            SimpleUtils.loadImageForView(mContext, mIvPointAvatarOne, subList.get(0).getAvatar(), R.drawable.img_official_avatar_android);
            SimpleUtils.loadImageForView(mContext, mIvPointAvatarThree, subList.get(2).getAvatar(), R.drawable.img_official_avatar_android);
            setText(mTvPointTwoName, subList.get(1).getNickName());
            setText(mTvPointOneName, subList.get(0).getNickName());
            setText(mTvPointThreeName, subList.get(2).getNickName());
            setText(mTvPointTwoNamePoint, subList.get(1).getPoints() + "");
            setText(mTvPointOneNamePoint, subList.get(0).getPoints() + "");
            setText(mTvPointThreeNamePoint, subList.get(2).getPoints() + "");
            if (adapter != null) {
                adapter.addHeaderView(headView);
                adapter.setHeaderWithEmptyEnable(true);
                if (adapter.hasEmptyView()) {
                    adapter.setUseEmpty(false);
                }
            }
        }
    }

    //领奖
    private void showLingQuDialog() {
        SeasonRewardDialog dialog = new SeasonRewardDialog(mContext);
        dialog.setOnclickListener(new SeasonRewardDialog.onGetRewardOnclickListener() {
            @Override
            public void onGetRewardClick() {
                //领取
                startActivity(new Intent(mContext, SelectSeasonRewardGetAddressActivity.class));
            }
        });
        dialog.show();
    }

    private void initRefreshData(String type, String season_id) {
        //下拉刷新
        mSmartLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                fresh(type, season_id);
            }
        });
        //加载更多
        mSmartLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                loadMore(type, season_id);
            }
        });
    }

    private void fresh(String type, String season_id) {
        mCount = 1;
        getPointIntergralRankData(type, season_id, mCount + "", limit, true);
    }

    private void loadMore(String type, String season_id) {
        mCount = mCount + 1;
        getPointIntergralRankData(type, season_id, mCount + "", limit, false);
    }

    private void initAdapter() {
        mRecyclerView.setLayoutManager(new LinearLayoutManager(mContext));
        adapter = new PointIntegralRankAdapter();
        adapter.setEmptyView(LayoutInflater.from(mContext).inflate(R.layout.recycler_view_empty, mRecyclerView, false));
        mRecyclerView.setAdapter(adapter);

    }

    //积分赛排名列表
    private void getPointIntergralRankData(String type, String season_id, String page, String limit, boolean fresh) {
        showLoadingDialog("");
        PhoneLive.getRankingList(getUserToken(), type, season_id, page, limit, new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                hideLoadingDialog();
                ToastUtils.showText(e.getMessage());
                freshFail(fresh);
            }

            @Override
            public void onResponse(String response, int id) {
                hideLoadingDialog();
                if (BaseUtils.isJSONValid(response)) {
                    try {
                        if (BaseUtils.codeIs0(mContext, response)) {
                            RankListBean json = gson.fromJson(response, RankListBean.class);
                            if (json != null) {
                                RankListBean.DataBean data = json.getData();
                                if (data != null) {
                                    if (fresh) {
                                        List<RankListBean.DataBean.AllSeasonBean> allSeason = data.getAllSeason();//筛选
                                        if (allSeason != null) {
                                            //发送eventbus粘性事件
                                            PointEvent event = new PointEvent();
                                            event.setData(allSeason);
                                            event.setType(0);
                                            EventBus.getDefault().postSticky(event);
                                        }
                                        RankListBean.DataBean.PersonalBean personal = data.getPersonal();//个人
                                        mLlBottom.setVisibility(personal != null && personal.getRank() != 0 ? View.VISIBLE : View.GONE);
                                        if (personal != null) {
                                            mTvBottomPaiming.setText(String.format(getString(R.string.string_bottom_point_paiming), personal.getRank()));
                                            SimpleUtils.loadImageForView(mContext, mIvBottomAvatar, personal.getAvatar(), R.drawable.img_official_avatar_android);
                                            setText(mTvBottomName, personal.getNickName());
                                            setText(mTvBottomPointSaijiIntegration, personal.getPoints() + "");
                                        }
                                        boolean receive = data.isReceive();
                                        if (receive) {
                                            showLingQuDialog();
                                        }
                                    }
                                    List<RankListBean.DataBean.PersonalBean> res = data.getRes();
                                    if (res != null) {
                                        if (fresh) {
                                            if (adapter != null && adapter.getHeaderLayoutCount() > 0) {
                                                adapter.removeAllHeaderView();
                                            }
                                            if (res.size() >= 3) {
                                                addHeader(adapter, res.subList(0, 3));
                                            } else {
                                                if (adapter.hasEmptyView()) {
                                                    adapter.setUseEmpty(true);
                                                }
                                            }
                                            adapter.setNewInstance(res);
                                            mSmartLayout.finishRefresh(true);
                                        } else {
                                            adapter.addData(res);
                                            adapter.notifyDataSetChanged();
                                            mSmartLayout.finishLoadMore(true);
                                        }
                                    } else freshFail(fresh);
                                } else freshFail(fresh);
                            } else freshFail(fresh);
                        } else freshFail(fresh);
                    } catch (JSONException e) {
                        freshFail(fresh);
                        e.printStackTrace();
                    }
                } else {
                    freshFail(fresh);
                    ToastUtils.showText(getString(R.string.string_response_error));
                }
            }
        });
    }


    //刷新失败
    private void freshFail(boolean fresh) {
        if (fresh) {
            adapter.setNewInstance(null);
            mSmartLayout.finishRefresh(false);
        } else {
            mSmartLayout.finishLoadMore(false);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void Event(MessageEvent event) {
        String message = event.getMessage();
        int typeInt = event.getType();
        if (typeInt == 0) {
            season_id = message;
            initRefreshData(type, season_id);
            fresh(type, season_id);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        //解除注册EventBus
        EventBus.getDefault().unregister(this);
        OkHttpUtils.getInstance().cancelTag(this);
    }

    @Override
    public void onPause() {
        super.onPause();
        if (getActivity() != null) {
            // 页面埋点
            StatService.onPageEnd(getActivity(), "积分简中榜单tab");
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (getActivity() != null) {
            // 页面埋点
            StatService.onPageStart(getActivity(), "积分简中榜单tab");
        }
        season_id = "";
        initRefreshData(type, season_id);
        fresh(type, season_id);
    }

}
